import { QueryRunner } from "typeorm"
import { QueuedApiTrace } from "@common/types"
import { Alert, ApiEndpoint, OpenApiSpec } from "models"
import { MetloContext } from "types"
import { getEntityManager } from "services/database/utils"
import { createSpecDiffAlerts } from "services/alert/openapi-spec"
import mlog from "logger"

export const findOpenApiSpecDiff = async (
  ctx: MetloContext,
  trace: QueuedApiTrace,
  endpoint: ApiEndpoint,
  queryRunner: QueryRunner,
  validationErrors: Record<string, string[]>,
): Promise<Alert[]> => {
  try {
    if (
      !validationErrors ||
      !endpoint.openapiSpecName ||
      endpoint.openapiSpecName.endsWith("-generated")
    ) {
      return []
    }
    const openApiSpec = await getEntityManager(ctx, queryRunner).findOneBy(
      OpenApiSpec,
      {
        name: endpoint.openapiSpecName,
      },
    )
    if (!openApiSpec || openApiSpec?.isAutoGenerated) {
      return []
    }

    return await createSpecDiffAlerts(
      ctx,
      validationErrors,
      endpoint.uuid,
      trace,
      openApiSpec,
      queryRunner,
    )
  } catch (err) {
    mlog.withErr(err).error("Error finding OpenAPI Spec diff")
    return []
  }
}
